package main

import (
	"Godzilla/conf/databases"
	"Godzilla/tcp/proto"
	"bufio"
	"fmt"
	"io"
	"log"
	"net"
	"sync"
)

type Node struct {
	//客户端地址
	Address    	string
	//客户端连接
	Conn 		net.Conn
	//数据
	DataQueue	chan []byte
}

var (
	ClientMap map[string]*Node = make(map[string]*Node, 0)
	RWLocker sync.RWMutex
)

func main()  {
	var (
		Host    string
		Port    string
		address string
	)

	//读取tcpServer配置
	databases.TcpSetConfig()
	Host = databases.GetTcpConfig("Host")
	Port = databases.GetTcpConfig("Port")
	log.Println("Host:", Host)
	log.Println("Port:", Port)

	//开放端口
	hawkServer, err := net.ResolveTCPAddr("tcp", Host+":"+Port)
	if err != nil {
		log.Println("初始化服务端tcp套接字报错:", err.Error())
	}

	listen, err := net.ListenTCP("tcp", hawkServer)
	//listen, err := net.Listen("tcp", Host+":"+Port)
	if err != nil {
		log.Println("tcp监听端口报错:",err.Error())
		return
	}
	defer listen.Close()

	for  {
		conn, err := listen.Accept() //接受连接
		if err != nil {
			log.Println("接受连接报错:",err.Error())
			continue
		}

		address = conn.RemoteAddr().String()
		log.Println("客户端连接地址:",address)
		node := &Node{
			Address:   address,
			Conn:      conn,
			DataQueue: make(chan []byte, 50),
		}

		RWLocker.Lock()
		//判断数据目标对象在哪个服务端，然后拿取句柄发送到目标客户端
		ClientMap[conn.RemoteAddr().String()] = node
		RWLocker.Unlock()

		go process(conn)

	}
}

func process(conn net.Conn)  {
	defer conn.Close()//关闭连接
	reader := bufio.NewReader(conn)
	for  {
		msg, err := proto.Decode(reader)

		fmt.Println("收到消息：", msg)
		if err == io.EOF {
			return
		}
		if err != nil {
			fmt.Println("decode失败，err:", err)
			return
		}
		b, err := proto.Encode(string(msg))
		if err != nil {
			fmt.Println("Encode失败，err:", err)
			return
		}
		conn.Write(b)




		//
		//var buf [128]byte
		//n, err := reader.Read(buf[:]) // 读取数据
		//if err != nil {
		//	RWLocker.Lock()
		//	delete(ClientMap, address)
		//	RWLocker.Unlock()
		//	fmt.Println("read from client failed, err:", err)
		//	break
		//}
		//recvStr := string(buf[:n])
		//fmt.Println("收到client端发来的数据：", recvStr)






		//msg, err := proto.Decode(reader)
		//if err == io.EOF {
		//	return
		//}
		//if err != nil {
		//	log.Println("读取报错:",err.Error())
		//	return
		//}
		//log.Println("收到client端发来的数据:", msg)

		//休眠2秒给客户端发送数据
		//time.Sleep(time.Duration(2) * time.Second)
		//conn.Write([]byte("休眠2秒从服务端发送给客户端的消息"))
	}
}
